package com.archive.forum.controller;

import com.archive.forum.dto.NotificationDTO;
import com.archive.forum.dto.ResultDTO;
import com.archive.forum.enums.NotificationTypeEnum;
import com.archive.forum.exception.ExceptionEnum;
import com.archive.forum.model.User;
import com.archive.forum.service.NotificationService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

@Controller
public class NotificationController {
    @Autowired
    private NotificationService notificationService;
    @GetMapping("/notification/{id}")
    public String notification(@PathVariable(name = "id") Integer id, Model model, HttpServletRequest request) {

        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        NotificationDTO notificationDTO = notificationService.read(id,user);
        if (Objects.equals(NotificationTypeEnum.REPLY_COMMENT.getType(), notificationDTO.getType()) ||
                Objects.equals(NotificationTypeEnum.REPLY_POST.getType(), notificationDTO.getType())) {
            return "redirect:/post/" + notificationDTO.getOuterId();
        }else {
            return "redirect:/";
        }
    }
    @GetMapping("/notifications/unread-count")
    @ResponseBody
    public ResultDTO getUnreadCount(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        int un= notificationService.unreadCount(user.getId());
        return ResultDTO.okOf(un);
    }

    @PostMapping("/notification/markAllAsRead")
    @ResponseBody
    public ResultDTO markAllAsRead(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return ResultDTO.errorOf(ExceptionEnum.NOT_LOGIN);
        }

        notificationService.markAsRead(user.getId());
        return ResultDTO.okOf();
    }

    @PostMapping("/notification/deleteAll")
    @ResponseBody
    public ResultDTO deleteAllNotifications(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return ResultDTO.errorOf(ExceptionEnum.NOT_LOGIN);
        }

        notificationService.deleteAllNotifications(user.getId());
        return ResultDTO.okOf();
    }
}
